package com.gps.web.action.sheets;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.gps.web.comm.Unility;
import com.gps.web.comm.action.BaseSheetAction;
import com.gps.web.dao.sheet.GpsDeviceDao;
import com.gps.web.entity.sheets.GpsDevice;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.*;
import org.apache.struts2.ServletActionContext;

public class GpsDeviceAction extends BaseSheetAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Resource
	private GpsDeviceDao gpsDeviceDao;

	static Logger logger = Logger
			.getLogger(GpsDeviceAction.class.getName());

	private String deviceID; //设备ID号
	private String putawayDate; //入库日期
	private String deviceModelNum; //设备型号
	private List<GpsDevice> gpsDeviceList;

	public String execute() {
		gpsDeviceList = gpsDeviceDao.findAll();
		
		return SUCCESS;
	}
	
	public String search() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("deviceID", deviceID);
		map.put("putawayDate", putawayDate);
		map.put("deviceModelNum", deviceModelNum);
		
		gpsDeviceList = gpsDeviceDao.getGpsDeviceByPage(map);
		
		return SUCCESS;
	}
	
	public String uploadSheet() throws Exception {
		if(StringUtils.isBlank(spreadSheetFileName)) {
			setOutMessage("请选择要上传的文件！");
			return INPUT;
		}
		if(!spreadSheetFileName.endsWith(".xls") && !spreadSheetFileName.endsWith(".xlsx")) {
			setOutMessage("文件格式错误，请上传.xls或.xlsx为后缀的excel文件！");
			return INPUT;
		}
		
		String filePath = ServletActionContext.getServletContext().getRealPath(com.gps.web.comm.GlobalConstants.UPLOAD_PATH + spreadSheetFileName);
		
		SaveFile(filePath);

		if(!validateFileData(filePath)) return INPUT;

		List<GpsDevice> gdList = new ArrayList<GpsDevice>();

		if(!ReadDataToBuildEntity(gdList, filePath)) return INPUT;

		SaveRecords(gdList);

		gpsDeviceList = gpsDeviceDao.findAll();
		
		return SUCCESS;
	}

	@Override
	protected void initSheetHeader() {
		colHeaderList.add(new ColumnHeader("入库日期"));
		colHeaderList.add(new ColumnHeader("设备型号"));
		colHeaderList.add(new ColumnHeader("ID号"));
		colHeaderList.add(new ColumnHeader("设备提供厂商"));
		colHeaderList.add(new ColumnHeader("厂商联系人"));
		colHeaderList.add(new ColumnHeader("厂商联系方式"));
		colHeaderList.add(new ColumnHeader("经办人"));
		colHeaderList.add(new ColumnHeader("备注"));
	}
	
	private void SaveFile(String filePath) throws Exception
	{
		try {
			if(spreadSheet != null)
			{
				File destFile= new File(filePath);
				Unility.UploadFile(spreadSheet, destFile);
			}
		} catch (Exception e) {
			throw e;
		}
	}

	private boolean validateFileData(String filePath)
			throws FileNotFoundException {
		
		InputStream inp = new FileInputStream(filePath);
		XSSFWorkbook wb;
		try {
			wb = new XSSFWorkbook(inp);
		} catch (Exception e) {
			setOutMessage("文件读取失败，请重新上传！");
			return false;
		}
		XSSFSheet sheet = wb.getSheetAt(0);
		if(sheet == null || sheet.getRow(0) == null){
			setOutMessage("文件内容为空，请重新上传！");
			return false;
		}
		if(!validateSheetHeader(sheet.getRow(0))){
			setOutMessage("文件标题列格式错误，请重新上传！");
			return false;
		}
		
		return true;
	}
	
	private boolean ReadDataToBuildEntity(List<GpsDevice> gdList, String filePath)
			throws FileNotFoundException {
		InputStream inp = new FileInputStream(filePath);
		XSSFWorkbook wb;
		try {
			wb = new XSSFWorkbook(inp);
		} catch (Exception e) {
			return false;
		}
		XSSFSheet sheet = wb.getSheetAt(0);
		// 循环行Row
		for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
			XSSFRow row = sheet.getRow(rowNum);
			if (row == null) {
				continue;
			}

			GpsDevice gd = new GpsDevice();
			// 循环列Cell
			for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
				XSSFCell cell = row.getCell(cellNum);
				if (cell == null) {
					continue;
				}
				switch (cellNum) {
				case 0:
					gd.setPutawayDate(cell.getDateCellValue());
					break;
				case 1:
					gd.setDeviceModelNum(getValue(cell));
					break;
				case 2:
					gd.setDeviceID(getValue(cell));
					break;
				case 3:
					gd.setVendor(getValue(cell));
					break;
				case 4:
					gd.setVendorContact(getValue(cell));
					break;
				case 5:
					gd.setVendorContactPhone(getValue(cell));
					break;
				case 6:
					gd.setAgent(getValue(cell));
					break;
				case 7:
					gd.setRemarks(getValue(cell));
					break;
				default:
					break;
				}
			}
			gdList.add(gd);
		}
		return true;
	}

	private Boolean SaveRecords(List<GpsDevice> gdList) {
		for (int i = 0; i < gdList.size(); i++) {
			gpsDeviceDao.saveOrUpdate(gdList.get(i));
		}
		return true;
	}

	private String getValue(XSSFCell cell) {
		if (cell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
			return new DecimalFormat("#.##").format(cell.getNumericCellValue());
		} else if (cell.getCellType() == XSSFCell.CELL_TYPE_FORMULA) {
			return cell.getCellFormula();
		} else if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
			return cell.getStringCellValue();
		} else {
			return cell.toString();
		}
	}

	
	public String getDeviceID() {
		return deviceID;
	}

	public void setDeviceID(String deviceID) {
		this.deviceID = deviceID;
	}

	public String getPutawayDate() {
		return putawayDate;
	}

	public void setPutawayDate(String putawayDate) {
		this.putawayDate = putawayDate;
	}

	public String getDeviceModelNum() {
		return deviceModelNum;
	}

	public void setDeviceModelNum(String deviceModelNum) {
		this.deviceModelNum = deviceModelNum;
	}

	public List<GpsDevice> getGpsDeviceList() {
		return gpsDeviceList;
	}

	public void setGpsDeviceList(List<GpsDevice> gpsDeviceList) {
		this.gpsDeviceList = gpsDeviceList;
	}

}
